<template>
	<view class="body">
		<myHeader :title="title"></myHeader>
		<view class="content">
			<uni-collapse accordion="true">
			    <uni-collapse-item v-for="(item,index) in rolse" :key="index" :title="item.deptName">
					
					 <uni-data-checkbox :multiple="true" v-model="roleIds[index]" 
						@change="changedata"
						:localdata="dataService(item.roleMenuChild)" ></uni-data-checkbox>
			        <!-- <view style="padding: 30rpx;"
					v-for="(child,childIndex) in item.roleMenuChild" :key="childIndex"
					   >
			        </view> -->
			    </uni-collapse-item>
			</uni-collapse>
			 <button type="default" @click="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import {getRoles} from '../../api/api_roles.js'
	import {andUserRole} from '../../api/api_userInfo.js'
	import myHeader from '../components/head.vue'
	export default {
		data() {
			return {
				title:"添加部门",
				user:{},
				rolse:[],
				roleIds:[
				],
			}
		},
		components:{
			myHeader
		},onLoad(query){
			console.log(query)
			let _this = this;
			this.user = JSON.parse(query.item);
			getRoles().then(res=>{
			console.log(res)
				_this.rolse = res
			})
		},watch:{
			roleIds(valnew,valold){
				/**
				 * 多选问题：1、如果选择新的值 原有的值可能会被覆盖
				 * 			2、如果取消选择值 会出现同样问题
				 * 解决：改变结构，形成多层array
				 */
				/* 
					let idlist = [];
					valnew.forEach(childid=>{
						childid.forEach(item=>{
							idlist.push(item);//添加
						})
					})
					console.log(idlist)
					 */
			}
		},
		mounted() {
			
		},
		methods: {
			dataService(child){
				let data = [];
				child.forEach(val=>{
					data.push({"value": val.roleId,"text":val.deptName})
				})
				return data
			},changedata(val1,val2){
			},submit(){
				let _this = this;
				uni.showModal({
				    title: '提示',
				    content: `确认提交 ${_this.user.realName} 的角色吗`,
				    success: function (res) {
				        if (res.confirm) {
				           let idlist = [];
				           _this.roleIds.forEach(childid=>{
				           	childid.forEach(item=>{
				           		idlist.push(item);//添加
				           	})
				           })
				           andUserRole({"userId":_this.user.userId,"roleIds":idlist}).then( r=>{
							   uni.showToast({
							   	title:"成功",
								icon:"success",
								duration:2000,
								success() {
									uni.navigateBack({
										delta: 1
									})
								}
							   })
				           })
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			}
		}
	}
</script>

<style scoped style="scss">
	.content{
		
		/deep/ .uni-collapse{
			.checklist-group{
				display: block !important;
			}
		}
	}
</style>
